package com.treasure.mall.biz.service.core.impl;

import com.alibaba.fastjson.JSON;
import com.treasure.mall.biz.bo.BaseConfig;
import com.treasure.mall.biz.bo.config.BasicsConfig;
import com.treasure.mall.biz.bo.config.SignConfig;
import com.treasure.mall.biz.bo.config.WithdrawConfig;
import com.treasure.mall.biz.bo.config.ZbConfig;
import com.treasure.mall.biz.entity.BaseConfigPO;
import com.treasure.mall.biz.entity.common.CityAreaPO;
import com.treasure.mall.biz.repository.BaseConfigRepository;
import com.treasure.mall.biz.repository.common.CityAreaRepository;
import com.treasure.mall.biz.service.core.BaseConfigService;
import com.treasure.mall.zbq.common.ObjectUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 *
 * +---------------------------------------------------------
 * * @package: com.treasure.mall.biz.service.core.impl
 * * @author: guomw (guomwchen@foxmail.com)
 * * @date: 2020/6/11 15:01
 * * @since: V1.0.0
 * +---------------------------------------------------------
 * 注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的
 * Copyright 2019-2022 com.treasure.mall.biz.service.core.impl Inc. All rights reserved.
 */
@Service
@Slf4j
public class BaseConfigServiceImpl implements BaseConfigService {

    @Resource
    private BaseConfigRepository baseConfigRepository;
    @Resource
    private CityAreaRepository cityAreaRepository;
    /**
     * 单例模式，私有变量缓存
     */
    private static BaseConfig baseConfigCached;

    @Override
    public boolean exist() {
        return baseConfigRepository.findFirstByOrderByConfigId() != null;
    }


    /**
     * 获取系统配置
     *
     * @return BaseConfig
     */
    @Override
    public synchronized BaseConfig getConfig() {
        return getConfig(false);
    }

    @Override
    public synchronized BaseConfig getConfig(boolean fromCache) {
        try {
            if (fromCache) {
                if (baseConfigCached != null) {
                    return baseConfigCached;
                }
            }
            BaseConfig config = new BaseConfig();
            BaseConfigPO configPO = baseConfigRepository.findFirstByOrderByConfigId();
            if (configPO == null) {
                configPO = new BaseConfigPO();
            }

            /**
             * 基础配置
             */
            if (!ObjectUtils.isEmpty(configPO.getBasicsConfig())) {
                config.setBasicsConfig(JSON.parseObject(configPO.getBasicsConfig(), BasicsConfig.class));
            } else {
                config.setBasicsConfig(new BasicsConfig());
            }
            //提现配置
            if (!ObjectUtils.isEmpty(configPO.getWithdrawConfig())) {
                config.setWithdrawConfig(JSON.parseObject(configPO.getWithdrawConfig(), WithdrawConfig.class));
            } else {
                config.setWithdrawConfig(new WithdrawConfig());
            }
            //甄宝配置
            if (StringUtils.isNotBlank(configPO.getZbConfig())) {
                config.setZbConfig(JSON.parseObject(configPO.getZbConfig(), ZbConfig.class));
            } else {
                config.setZbConfig(new ZbConfig());
            }

            /**
             * 签到配置
             */
            if (StringUtils.isNotBlank(configPO.getSignConfig())) {
                config.setSignConfig(JSON.parseObject(configPO.getSignConfig(), SignConfig.class));
            } else {
                config.setSignConfig(new SignConfig());
            }


            baseConfigCached = config;
            return config;
        } catch (Exception e) {
            log.error("getConfig 异常", e);
            return new BaseConfig();
        }
    }

    /**
     * 保存系统配置
     *
     * @param baseConfig BaseConfig
     * @author guomw
     **/
    @Override
    public void save(BaseConfig baseConfig) {
        BaseConfigPO configPO = baseConfigRepository.findFirstByOrderByConfigId();
        if (configPO == null) {
            configPO = new BaseConfigPO();
        }
        /**
         * 基本配置
         */
        if (baseConfig.getBasicsConfig() != null) {
            configPO.setBasicsConfig(JSON.toJSONString(baseConfig.getBasicsConfig()));
        }

        //提现配置
        if (!ObjectUtils.isEmpty(baseConfig.getWithdrawConfig())) {
            configPO.setWithdrawConfig(JSON.toJSONString(baseConfig.getWithdrawConfig()));
        }


        //甄宝配置
        if (!ObjectUtils.isEmpty(baseConfig.getZbConfig())) {
            configPO.setZbConfig(JSON.toJSONString(baseConfig.getZbConfig()));
        }


        baseConfigRepository.saveAndFlush(configPO);
        baseConfigCached = getConfig(false);
    }

    @Override
    public List<CityAreaPO> getCities(Integer pid) {
        return cityAreaRepository.findByPid(pid);
    }


    @Override
    public ZbConfig getZbConfig() {
        ZbConfig config = new ZbConfig();
        BaseConfigPO configPO = baseConfigRepository.findFirstByOrderByConfigId();
        if (configPO == null) {
            configPO = new BaseConfigPO();
        }
        //甄宝配置
        if (StringUtils.isNotBlank(configPO.getZbConfig())) {
            return JSON.parseObject(configPO.getZbConfig(), ZbConfig.class);
        }
        return config;
    }


    /**
     * 签到配置
     *
     * @return
     */
    @Override
    public SignConfig getSignConfig() {
        SignConfig config = new SignConfig();
        BaseConfigPO configPO = baseConfigRepository.findFirstByOrderByConfigId();
        if (configPO == null) {
            configPO = new BaseConfigPO();
        }
        //签到配置
        if (StringUtils.isNotBlank(configPO.getSignConfig())) {
            return JSON.parseObject(configPO.getSignConfig(), SignConfig.class);
        }
        return config;
    }


    @Override
    public BasicsConfig getBasicsConfig() {
        BasicsConfig config = new BasicsConfig();
        BaseConfigPO configPO = baseConfigRepository.findFirstByOrderByConfigId();
        if (configPO == null) {
            configPO = new BaseConfigPO();
        }
        //基本配置
        if (StringUtils.isNotBlank(configPO.getBasicsConfig())) {
            return JSON.parseObject(configPO.getBasicsConfig(), BasicsConfig.class);
        }
        return config;
    }

    /**
     * 保存签到配置
     *
     * @param signConfig
     * @return
     */
    @Override
    public SignConfig saveSignConfig(SignConfig signConfig) {
        BaseConfigPO configPO = baseConfigRepository.findFirstByOrderByConfigId();
        if (configPO == null) {
            configPO = new BaseConfigPO();
        }
        //签到配置
        if (!ObjectUtils.isEmpty(signConfig)) {
            configPO.setSignConfig(JSON.toJSONString(signConfig));
        }
        baseConfigRepository.saveAndFlush(configPO);
        return signConfig;
    }


    /**
     * 执行甄宝打假任务
     */
    @Override
    public void execDjTask() {
        try {
            /**
             * 1、首先判断是否上次执行时间，如果为空，则立即执行添加，结束本次任务
             * 2、如果上次执行时间不为空，判断当前时间是否大于上次时间指定分钟。如果不是，则结束本次任务
             * 3、如果当前时间大于上次执行时间n分钟，则判断当天添加的数量是否大于等于指定数量，如果是，则结束本次任务
             *
             */

            ZbConfig config = getZbConfig();
            if (config.getLastTime() == null) {
                addDjCount(config);
                return;
            }
            //判断上次执行时间是否是昨天，如果是昨天，则重置当前添加数量
            if (compareOneAndYesterday(config.getLastTime().format(DateTimeFormatter.ofPattern("yyyy-MM-dd")).toString())) {
                config.setToDayAddCount(0);
            }
            // 如果当前时间大于上次执行时间n分钟，
            if (config.getLastTime().plusMinutes(config.getAddFrequency()).compareTo(LocalDateTime.now()) < 0 && config.getToDayAddCount() < config.getToDayMaxAddCount()) {
                addDjCount(config);
            }

        } catch (Exception e) {
            log.error("execDjTask", e);
        }
    }

    /**
     * 添加打假数量
     *
     * @param config
     */
    public void addDjCount(ZbConfig config) {
        config.setCurrentDjCount(config.getCurrentDjCount() + 1);
        config.setToDayAddCount(config.getToDayAddCount() + 1);
        config.setLastTime(LocalDateTime.now());
        BaseConfig baseConfig = new BaseConfig();
        baseConfig.setZbConfig(config);
        save(baseConfig);
    }

    /***
     * 比较参数的值是否是昨天（是昨天返回 true）
     * @param oneTime
     * @return
     */
    public static boolean compareOneAndYesterday(String oneTime) {
        //
        if (oneTime == null) {
            return false;
        }
        //获得昨天的值
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        String twoTime = sdf.format(calendar.getTime());
        //比较
        return oneTime.equals(twoTime);
    }
}
